<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules" class="el-form">
      <el-form-item label="关联批次名称：" prop="batchId" class="w100p">
        <el-select v-model="formData.batchId" filterable clearable placeholder="请选择关联批次" :disabled="!!batchId" @change="changeBatch">
          <el-option v-for="item in batchList" :key="item.batchId" :label="item.batchName" :value="item.batchId" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号：" prop="batchNo" class="w100p">
        <el-input :value="formData.batchNo" disabled placeholder="请选择关联批次" />
      </el-form-item>
      <el-form-item label="加工作业名称：" prop="taskName" class="w100p">
        <el-input :value="formData.taskName" disabled placeholder="请选择关联批次" />
      </el-form-item>
      <el-form-item label="加工产品：" prop="productId" class="w100p">
        <el-select v-model="formData.productId" disabled placeholder="请选择关联批次">
          <el-option v-for="item in productList" :key="item.productId" :label="item.productName" :value="item.productId" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联产线：" prop="productLineId" class="w100p">
        <el-select v-model="formData.productLineId" filterable clearable placeholder="请选择关联产线">
          <el-option v-for="item in productLineList" :key="item.productLineId" :label="item.productLineName" :value="item.productLineId" />
        </el-select>
      </el-form-item>
      <el-form-item label="预期加工量：" prop="processingVolume" class="w100p">
        <div class="input-group">
          <el-input-number :precision="0" v-model="formData.processingVolume" type="number" :min="0" placeholder="预估批次加工总量" clearable @input="changeProcessingVolume" />
          <div class="el-input-group__append">{{ prodUnitName }}</div>
        </div>
      </el-form-item>
      <el-form-item label="预期开始时间：" prop="startTime" class="w100p">
        <el-date-picker v-model="formData.startTime" type="date" placeholder="请选择预期开始时间" />
      </el-form-item>
      <el-form-item label="预期结束时间：" prop="endTime" class="w100p">
        <el-date-picker v-model="formData.endTime" type="date" placeholder="请选择预期结束时间" />
      </el-form-item>
      <el-form-item label="处理人：" prop="processName" class="w100p">
        <el-input v-model="formData.processName" placeholder="请输入处理人" />
      </el-form-item>
      <el-form-item label="操作人：" prop="operatorPersonNo" class="w100p">
        <el-select v-model="formData.operatorPersonNo" placeholder="请选择操作人" @change="changePerson">
          <el-option v-for="item in personList" :key="item.personNo" :label="item.person.name" :value="item.personNo" />
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="materialList.length !== 0" class="material-list">
      <div v-for="(item, index) in materialList" :key="index" class="list-item">
        <span>加工原料：{{ item.materialName }}</span>
        <span>预计领料数量：<el-input v-model="item.expectNum" placeholder="请输入预计领料数量" /> {{ item.unitName || item.material.unitName }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import apiBatch from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import api from '@/api/processing-management/process-task-manage/index';
import { getToken } from '@/utils/auth';
export default {
  components: {},
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    },
    batchId: {
      type: [Number, null],
      default: null
    },
    productList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    productLineList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    batchList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    personList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      formDataDefault: {
        batchId: '',
        batchNo: '',
        taskName: '',
        productId: '',
        productLineId: '',
        processingVolume: '',
        startTime: '',
        endTime: '',
        processName: '',
        operatorPersonNo: ''
      },
      formData: {},
      saveLoading: false,
      showDialog: false,
      rules: {
        batchId: [
          {
            required: true,
            message: '请选择关联批次'
          }
        ],
        batchNo: [
          {
            required: true,
            message: '请选择关联批次'
          }
        ],
        taskName: [
          {
            required: true,
            message: '请选择关联批次'
          }
        ],
        productId: [
          {
            required: true,
            message: '请选择关联批次'
          }
        ],
        productLineId: [
          {
            required: true,
            message: '请选择关联产线'
          }
        ],
        processingVolume: [
          {
            required: true,
            message: '请填写预估批次加工总量'
          }
        ],
        startTime: [
          {
            required: true,
            message: '请选择预期开始时间'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择预期结束时间'
          }
        ],
        processName: [
          {
            required: true,
            message: '请输入处理人'
          }
        ],
        operatorPersonNo: [
          {
            required: true,
            message: '请选择操作人'
          }
        ]
      },
      processBatchNo: '',
      prodUnitName: '',
      materialList: []
    };
  },
  computed: {
    titleText() {
      return this.selectedItem ? '编辑工单' : '新增工单';
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    },
    batchId(v) {
      if (v) {
        this.changeBatch(v);
      }
    }
  },
  created() {
    this.reset();
    this.changeProcessingVolume = this.debounce(this.changeProcessingVolume, 300);
    if (this.batchId) {
      this.changeBatch(this.batchId);
      this.formData.batchId = this.batchId;
    }
  },
  mounted() {},
  methods: {
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.formDataDefault));
      this.prodUnitName = '';
      this.materialList = [];
    },
    init() {
      const { selectedItem, formData } = this;
      if (selectedItem) {
        for (const key in formData) {
          if (Object.hasOwnProperty.call(formData, key)) {
            formData[key] = selectedItem[key];
          }
        }
        this.materialList = selectedItem.taskRawMaterialList;
        const findProduct = this.productList.find(item => item.productId === selectedItem.productId);
        this.prodUnitName = findProduct.material.unitName;
      }
    },
    save() {
      const { formData, selectedItem } = this;
      const paylod = JSON.parse(JSON.stringify(formData));
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoading = true;
          paylod.startTime = this.$moment(paylod.startTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.endTime = this.$moment(paylod.endTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.taskRawMaterialList = this.materialList;
          if (selectedItem) {
            paylod.taskId = selectedItem.taskId;
            api
              .edit(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          } else {
            paylod.name = getToken('username');
            api
              .add(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    close() {
      setTimeout(() => {
        this.reset();
        this.$refs['form']?.resetFields();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
        this.$refs['form']?.resetFields();
      }, 250);
      this.$emit('input', false);
    },
    queryBomByProduct() {
      const { processingVolume, productId } = this.formData;
      if (processingVolume && productId) {
        apiBatch.queryBomByProduct(processingVolume, productId).then(res => {
          if (res.code === 1) {
            this.materialList = res.data;
          }
        });
      }
    },
    changeProcessingVolume(v) {
      this.queryBomByProduct();
    },
    debounce(fn, delay) {
      let timer = null;
      return function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, arguments);
        }, delay);
      };
    },
    changeBatch(v) {
      const findBatch = this.batchList.find(item => item.batchId === v);
      this.formData.batchNo = findBatch.batchNo;
      this.getTaskName(findBatch.batchName);
      this.formData.productId = findBatch.productId;
      const findProduct = this.productList.find(item => item.productId === findBatch.productId);
      this.prodUnitName = findProduct.material.unitName;
      this.queryBomByProduct();
    },
    changePerson(v) {
      const find = this.personList.find(item => item.personNo === v);
      this.formData.operatorName = find.person.name;
    },
    getTaskName(batchName) {
      api.getTaskName(batchName).then(res => {
        this.formData.taskName = res.data;
      });
    },
    validateForm() {
      const { formData } = this;
      const paylod = JSON.parse(JSON.stringify(formData));
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(async valid => {
          if (valid) {
            paylod.startTime = this.$moment(paylod.startTime).format('YYYY-MM-DD HH:mm:ss');
            paylod.endTime = this.$moment(paylod.endTime).format('YYYY-MM-DD HH:mm:ss');
            paylod.taskRawMaterialList = this.materialList;
            paylod.name = getToken('username');
            resolve(paylod);
          } else {
            resolve(null);
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
  > * {
    &:first-of-type {
      flex: 0 0 80%;
    }
  }
  .el-input-group__append {
    width: 100%;
    text-align: center;
    height: 100%;
  }
}
::v-deep .el-form-item {
  width: 100%;
  align-items: center !important;
}
::v-deep .el-form-item__label {
  min-width: 200px !important;
}
.material-list {
  margin-top: 24px;
  padding: 24px 47px;
  box-sizing: border-box;
  background: #e9f8fd;
  border-radius: 10px;
  border: 1px solid #c9e0e7;
  .el-input {
    width: 100px;
    margin: 0 10px;
  }
  .list-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    span {
      flex: 1;
      &:last-of-type {
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}
</style>
